package com.gcloud.googledrive;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
//import java.io.OutputStream;

import com.example.gcode.Archivos;
import com.example.gcode.GCloudSingleton;
import com.example.gcode.R;
import com.gcloud.dto.GCloudFile;
import com.gcloud.persistance.SQLiteHandler;
import com.gfilechooser.utils.FileUtils;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
//import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
//import com.google.api.client.http.FileContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.utils.Constants;
import com.utils.GCloudUtil;
import com.utils.Message;

import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
//import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class DownloadGoogleFileActivity extends Activity {

	private ProgressDialog pDialog;

	public static Drive service;
	GoogleAccountCredential credential;
	private static final int REQUEST_ACCOUNT = 1;
	private static final int REQUEST_CODE = 100;
	private static String TAG = DownloadGoogleFileActivity.class
			.getSimpleName();
	private static String key_ = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.archivos_list);
		credential = GoogleAccountCredential.usingOAuth2(
				DownloadGoogleFileActivity.this, DriveScopes.DRIVE);
		Bundle bundle = getIntent().getExtras();
		String account = "";
		String urlToDownload = "";
		String fileName="";
		String mimeType="";
		if (bundle != null) {
			DownloadGoogleFileActivity.key_ =bundle.getString(
					Constants.FILE_KEY);
			account = bundle.getString(Constants.FILE_ACCOUNT);
			urlToDownload = bundle.getString(Constants.FILE_URL);
			fileName = bundle.getString(Constants.FILE_NAME);
			mimeType= bundle.getString(Constants.FILE_MIMETYPE);
		}
		//if (account != null) {
			credential.setSelectedAccountName(account);
			service = getDriveServices(credential);
			new CargarArchivos().execute(key_, urlToDownload,fileName, mimeType);
//		}else{
//		startActivityForResult(credential.newChooseAccountIntent(),
//				REQUEST_ACCOUNT);
//		}
	}

	private void showChooser() {
		// Use the GET_CONTENT intent from the utility class
		Intent target = FileUtils.createGetContentIntent();
		// Create the chooser Intent
		Intent intent = Intent.createChooser(target,
				getString(R.string.chooser_title));
		try {
			startActivityForResult(intent, REQUEST_CODE);
		} catch (ActivityNotFoundException e) {
			// The reason for the existence of aFileChooser
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_upload:

			Log.i("here", "upload");
			showChooser();
			break;
		case R.id.menu_download:
			Log.i("here", "download");
			break;
		case R.id.menu_delete:
			Log.i("here", "delete");
			break;
		case R.id.menu_bookmark:
			Log.i("here", "bookmark");
			break;
		case R.id.menu_save:
			Log.i("here", "save");
			break;
		case R.id.menu_search:
			Log.i("here", "search");
			break;
		case R.id.menu_google_drive:
			Log.i("here", "google drive");
			break;
		case R.id.menu_dropbox:
			Log.i("here", "dropbox");
			break;
		}
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.layout.menu_layout, menu);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_ACCOUNT:
			if (resultCode == RESULT_OK && data != null
					&& data.getExtras() != null) {
				String accountName = data
						.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
				credential.setSelectedAccountName(accountName);
				DownloadGoogleFileActivity.service = getDriveServices(credential);
				SQLiteHandler sqliteHandler = new SQLiteHandler(
						DownloadGoogleFileActivity.this, Constants.GCLOUD,
						null, Constants.DB_VERSION);

				CargarArchivos downloadGoogleFile = new CargarArchivos();
				GCloudFile fileToDownload = sqliteHandler
						.getFile(DownloadGoogleFileActivity.key_);
				// GCloudFile fileToDownload = GCloudUtil
				// .getSelected(DownloadGoogleFileActivity.key_);
				if (fileToDownload != null
						&& fileToDownload.getAccount().equals(Constants.GOOGLE)) {
					downloadGoogleFile.setFile(
							GCloudUtil.gCloudFileToGoogleDrive(fileToDownload),
							DownloadGoogleFileActivity.service);
					downloadGoogleFile.execute();
				}
				Log.i("OnActivitty", "after execute");

			}
			break;
		}
	}

	private Drive getDriveServices(GoogleAccountCredential credential) {
		return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
				new GsonFactory(), credential).build();
	}

	public void showToast(final String toast) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), toast,
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	class CargarArchivos extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(DownloadGoogleFileActivity.this);
			pDialog.setMessage(Message.CHARGING_FILES);
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		Uri uri;
		GCloudSingleton gCloudSingleton;
		String answer = "false";
		Drive gService;
		File file;

		protected void setFile(File file, Drive service) {
			this.file = file;
			this.gService = service;
		}

		/**
		 * getting Inbox JSON
		 * */
		protected String doInBackground(String... params) {
			String fkey_=params[0];
			String urlToDownload=params[1];
			String fileName=params[2];
			String mimeType=params[3];
			Log.i("GCLOUD", "Ya entre a doInBackground :)");
			String methodName = "doInBackground()";
			Log.i(TAG, methodName);
//			if (file.getDownloadUrl() != null
//					&& file.getDownloadUrl().length() > 0) {
//				String download = file.getDownloadUrl();
				Log.i("Download URL: ", urlToDownload);
				GenericUrl gurl = new GenericUrl(
						urlToDownload);
				try {
					HttpResponse resp = DownloadGoogleFileActivity.service
							.getRequestFactory().buildGetRequest(gurl)
							.execute();
					Log.i(TAG, "Everything goes well");
					// TODO flush here
					if (resp.getContent() != null) {
						Log.i("Downloading file: ",
								"everything looks good: "
										+ resp.getStatusCode() + " : "
										+ resp.getStatusMessage());
					}
					writeFile(fileName, mimeType,
							resp.getContent());
					openFile(fileName, mimeType);
				} catch (IOException e) {
					Log.e(TAG, "IOException downloading: " + e);
					return "false";
				}
//			} else {
//				Log.i(TAG, "Is not a download file getDownloadUrl() = null");
//				return "false";
//			}
			return "true";
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			if (file_url.equalsIgnoreCase("true")) {
				showToast(Message.FILE_DOWNLOADED);
//				Intent newIntent = new Intent(DownloadGoogleFileActivity.this,
//						Archivos.class);
//				startActivity(newIntent);
			} else {
				showToast(Message.ERROR_DOWNLOADING_FILE);
			}

			// if(){
			// startActivityForResult(credential.newChooseAccountIntent(),
			// REQUEST_ACCOUNT);
			// }
			// updating UI from Background Thread
		}

	}

	private void writeFile(String name, String mimeType, InputStream inputStream)
			throws IOException {
		// java.io.File files=new java.io.File(Environment.DIRECTORY_DOWNLOADS,
		// name);
		java.io.File files = android.os.Environment
				.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
		FileOutputStream outPutStream = new FileOutputStream(files + "/" + name);
		int byteReaded = 0;
		byte[] bytes = new byte[1024];
		try {
			while ((byteReaded = inputStream.read(bytes)) != -1) {
				outPutStream.write(bytes, 0, byteReaded);
			}
			Log.i("Downloading file: ", "File writed success");
		} catch (Exception e) {
			Log.i("DownloadGoogleFileActivity",
					"exception downloading the file: " + name);
		} finally {
			outPutStream.close();
		}

	}

	private void openFile(String name, String mimeType) {
		try {
			java.io.File file = android.os.Environment
					.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
			java.io.File path = new java.io.File(file, name);
			Uri uri = Uri.fromFile(path);
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(uri, mimeType);
			startActivity(intent);
		} catch (Exception e) {
			Log.i("Clicke init: ", "Error: " + e);
		}
	}

}